package com.brillilab.service.logic.comments;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.brillilab.common.alioss.OssFileEnum;
import com.brillilab.common.entity.PageVo;
import com.brillilab.common.utils.MyBeanUtils;
import com.brillilab.domain.enums.comments.CommentsClassifyEnum;
import com.brillilab.domain.enums.comments.CommentsContentTypeEnum;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.enums.lab.LabMemberEnum;
import com.brillilab.domain.po.comments.ChatMessage;
import com.brillilab.domain.po.comments.Comments;
import com.brillilab.domain.po.experiments.Experiment;
import com.brillilab.domain.po.lab.LabMember;
import com.brillilab.domain.po.system.FileManage;
import com.brillilab.domain.po.topics.Topic;
import com.brillilab.domain.po.topics.TopicDirection;
import com.brillilab.domain.po.topics.TopicExperiment;
import com.brillilab.domain.po.topics.TopicMember;
import com.brillilab.domain.po.topics.TopicTarget;
import com.brillilab.domain.vo.comments.ChatClassifySearchVo;
import com.brillilab.domain.vo.comments.ChatContentSearchVo;
import com.brillilab.domain.vo.comments.ChatFileSearchVo;
import com.brillilab.domain.vo.comments.ChatMemberListVo;
import com.brillilab.domain.vo.comments.ChatMessageAddVo;
import com.brillilab.domain.vo.comments.ChatMessageVo;
import com.brillilab.domain.vo.comments.ChatSearchClassifyVo;
import com.brillilab.domain.vo.comments.ChatSearchFileVo;
import com.brillilab.domain.vo.comments.CommentsAddVo;
import com.brillilab.domain.vo.comments.CommentsListVo;
import com.brillilab.domain.vo.comments.CommentsPagePaVo;
import com.brillilab.domain.vo.comments.ExperimentCardVo;
import com.brillilab.domain.vo.lab.MemberInfoVo;
import com.brillilab.domain.vo.team.TeamMemberVo;
import com.brillilab.service.core.comments.IChatMessageService;
import com.brillilab.service.core.comments.ICommentsService;
import com.brillilab.service.core.experiments.IExperimentService;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.plans.IPlanService;
import com.brillilab.service.core.system.IFileManageService;
import com.brillilab.service.core.topics.ITopicDirectionService;
import com.brillilab.service.core.topics.ITopicExperimentService;
import com.brillilab.service.core.topics.ITopicMemberService;
import com.brillilab.service.core.topics.ITopicService;
import com.brillilab.service.core.topics.ITopicTargetService;
import com.brillilab.service.logic.team.TeamLogic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class CommentsLogic {

	@Resource
	private ICommentsService commentsService;
	@Resource
	private IFileManageService fileManageService;
	@Resource
	private ILabMemberService labMemberService;
	@Resource
	private IChatMessageService chatMessageService;
	@Resource
	private IExperimentService experimentService;
	@Resource
	private TeamLogic teamLogic;
	@Resource
	private ITopicService topicService;
	@Resource
	private ITopicMemberService topicMemberService;
	@Resource
	private ITopicDirectionService topicDirectionService;
	@Resource
	private ITopicExperimentService topicExperimentService;
	@Resource
	private ITopicTargetService topicTargetService;
	@Resource
	private IPlanService planService;

	/**
	 * 添加评论
	 * 
	 * @param labMemberId
	 * @param addVo
	 * @return
	 */
	public Long addComments(Long labId, Long labMemberId, CommentsAddVo addVo) {
		Comments comments = MyBeanUtils.copyBean(addVo, Comments.class);
		comments.setLabMemberId(labMemberId);
		if(CommentsClassifyEnum.PLAN.getValue().equals(addVo.getClassify())) {
			comments.setRemark(String.valueOf(addVo.getPlanDate().getTime()));
		}
		commentsService.save(comments);
		if (addVo.getFileId() != null) {
			FileManage fileManage = new FileManage();
			fileManage.setId(addVo.getFileId());
			fileManage.setAttachType(OssFileEnum.CommentFile.getKey());
			fileManage.setReferDataId(comments.getId());
			fileManageService.updateById(fileManage);
		}
		
		// 送聊天消息给相关人
		this.asyncSendChat(labId, comments, addVo.getFileId(), null);
		return comments.getId();
	}

	// 异步送聊天消息给相关人
	private void asyncSendChat(Long labId, Comments comment, Long fileId, List<Long> noSendMemberIds) {
		try {
			Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					sendChatMessage(labId, comment, fileId, noSendMemberIds);
				}
			});
			thread.start();
		} catch (Exception e) {
			log.error("评论发送消息 {}", e);
		}
	}

	// 送聊天消息给相关人
	private void sendChatMessage(Long labId, Comments comment, Long fileId, List<Long> noSendMemberIds) {

		List<Long> toMemberIds = CollUtil.toList();
		String title = null;
		String figure = null;
		if (CommentsClassifyEnum.EXPERIMENT.getValue().equals(comment.getClassify())) {
			Experiment experiment = experimentService.selectById(comment.getClassifyId());
			if (!comment.getLabMemberId().equals(experiment.getExecutorId())) {
				toMemberIds.add(experiment.getExecutorId());
			}
			
			TopicTarget topicTarget = topicTargetService.selectById(experiment.getTopicTargetId());
			if(CommentsContentTypeEnum.CARD.getValue().equals(comment.getContentType())) {
				figure = topicTarget.getFigure();
				title = topicTarget.getName();
			}else {
				title = experiment.getName()+"//"+topicTarget.getName();
				String[] strArr = experiment.getName().split(":");
				if(strArr!=null && strArr.length>1 && StrUtil.isNotBlank(strArr[1])) {
					title = strArr[1]+"//"+topicTarget.getName();
				}
			}
		} else if (CommentsClassifyEnum.PLAN.getValue().equals(comment.getClassify())) {
			if (!comment.getLabMemberId().equals(comment.getClassifyId())) {
				toMemberIds.add(comment.getClassifyId());
			}
			Date planDate = new Date(Long.valueOf(comment.getRemark()));
			DateTime beginOfWeek = DateUtil.beginOfWeek(planDate);
			DateTime endOfWeek = DateUtil.endOfWeek(planDate);
			title = StrUtil
					.builder("计划 ", DateUtil.format(beginOfWeek, "MM.dd"), "~", DateUtil.format(endOfWeek, "MM.dd"))
					.toString();
		} else if (CommentsClassifyEnum.TOPIC.getValue().equals(comment.getClassify())) {
			Topic topic = topicService.selectById(comment.getClassifyId());
			Assert.isTrue(topic != null, "课题不存在");

			List<TopicMember> list = topicMemberService.selectListByTopicId(topic.getId());
			if (CollUtil.isNotEmpty(list)) {
				List<Long> topicMemberIds = list.stream().map(TopicMember::getLabMemberId).collect(Collectors.toList());
				toMemberIds.addAll(topicMemberIds);
			}
			figure = "课题";
			title = topic.getName();
		} else if (CommentsClassifyEnum.TOPIC_DIRECTION.getValue().equals(comment.getClassify())) {
			TopicDirection topicDirection = topicDirectionService.getById(comment.getClassifyId());
			Assert.isTrue(topicDirection != null, "研究内容不存在");

			List<TopicExperiment> list = topicExperimentService
					.getTopicExperimentListByDirectionId(topicDirection.getId());
			if (CollUtil.isNotEmpty(list)) {
				List<Long> topicMemberIds = list.stream().map(TopicExperiment::getExecutorId)
						.collect(Collectors.toList());
				toMemberIds.addAll(topicMemberIds);
			}
			figure = topicDirection.getFigure();
			title = topicDirection.getName();
		} else if (CommentsClassifyEnum.TOPIC_TARGET.getValue().equals(comment.getClassify())) {
			TopicTarget topicTarget = topicTargetService.selectById(comment.getClassifyId());
			Assert.isTrue(topicTarget != null, "实验流不存在");

			List<TopicExperiment> list = topicExperimentService.getTopicExperimentList(topicTarget.getId());
			if (CollUtil.isNotEmpty(list)) {
				List<Long> topicMemberIds = list.stream().map(TopicExperiment::getExecutorId)
						.collect(Collectors.toList());
				toMemberIds.addAll(topicMemberIds);
			}
			figure = topicTarget.getFigure();
			title = topicTarget.getName();
		}

		Long piMemberId = labMemberService.getOwner(labId).getId();
		toMemberIds.add(piMemberId);

		TeamMemberVo leader = teamLogic.getLeaderOfTeamMember(labId, comment.getLabMemberId());
		Long supMemberId = null;
		if (leader != null && !comment.getLabMemberId().equals(leader.getLabMemberId())) {
			supMemberId = leader.getLabMemberId();
			toMemberIds.add(leader.getLabMemberId());
		}
		toMemberIds = CollUtil.distinct(toMemberIds);

		if (CollUtil.isNotEmpty(toMemberIds)) {
			List<ChatMessage> messageList = CollUtil.toList();
			for (Long toMemberId : toMemberIds) {
				if (!comment.getLabMemberId().equals(toMemberId) && !CollUtil.contains(noSendMemberIds, toMemberId)) {
					ChatMessage message = new ChatMessage();
					message.setFromMemberId(comment.getLabMemberId());
					message.setToMemberId(toMemberId);
					message.setClassify(comment.getClassify());
					message.setClassifyId(comment.getClassifyId());
					message.setTitle(title);
					message.setFigure(figure);
					message.setContent(comment.getContent());
					message.setContentType(comment.getContentType());
					message.setFileId(fileId);
					message.setCommentId(comment.getId());
					message.setRemark(comment.getRemark());
					if (!CommentsContentTypeEnum.CARD.getValue().equals(comment.getContentType()) 
							&& toMemberId.equals(piMemberId) && supMemberId!=null && !piMemberId.equals(supMemberId)) {// 有组长，PI消息不提示
						message.setIsRead(BoolEnum.TRUE.getValue());
					}
					messageList.add(message);
				}
			}
			if (CollUtil.isNotEmpty(messageList)) {
				chatMessageService.saveBatch(messageList);
			}
		}
	}

	/**
	 * 删除评论
	 * 
	 * @param commentId
	 */
	public void delComments(Long commentId) {
		Comments comments = commentsService.getById(commentId);
		Assert.isTrue(comments != null, "评论数据不存在");
		commentsService.removeById(commentId);
		// 把聊天消息相关的评论标记为评论已删除
		chatMessageService.setCommentsDelete(commentId);
	}

	/**
	 * 获取评论列表
	 * 
	 * @param labMemberId
	 * @param classify    分类：1实验，2计划，3课题，4研究内容，5实验流
	 * @param classifyId  分类id( 1实验-实验ID, 2计划-计划人ID 3课题-课题ID, 4研究内容-研究内容ID,
	 *                    5实验流-实验流ID )
	 * @param type
	 * @return
	 */
	public List<CommentsListVo> getCommentList(Long labMemberId, Integer classify, Long classifyId, Integer type) {
		List<CommentsListVo> listVos = CollUtil.toList();
		List<Comments> commentList = commentsService.getCommentList(classify, classifyId, type);
		if (CollUtil.isNotEmpty(commentList)) {
			listVos.addAll(getCommentsVoList(commentList));
		}
		// 把聊天消息相关的评论标记为已读
		chatMessageService.setMessageRead(labMemberId, classify, classifyId);
		return listVos;
	}
	
	/**
	 * 获取评论分页列表
	 * 
	 * @param labMemberId
	 * @param paVo
	 * @return
	 */
	public PageVo<CommentsListVo> getCommentPage(Long labMemberId, CommentsPagePaVo paVo) {
		List<CommentsListVo> listVos = CollUtil.toList();
		PageVo<Comments> page = commentsService.getCommentPage(paVo);
		if (CollUtil.isNotEmpty(page.getContent())) {
			listVos.addAll(getCommentsVoList(page.getContent()));
		}
		// 把聊天消息相关的评论标记为已读
		chatMessageService.setMessageRead(labMemberId, paVo.getClassify(),paVo.getClassifyId());
		return new PageVo<CommentsListVo>(paVo.getPageNum(), paVo.getPageSize(), page.getTotalRow(), listVos);
	}

	// 获取评论VO列表
	private List<CommentsListVo> getCommentsVoList(List<Comments> commentList) {
		List<CommentsListVo> listVos = CollUtil.toList();
		List<Long> labMemberIds = commentList.stream().map(Comments::getLabMemberId).collect(Collectors.toList());
		List<MemberInfoVo> memberList = labMemberService.selectMemberVoListByIds(labMemberIds);
		Map<Long, List<MemberInfoVo>> memberMap = memberList.stream()
				.collect(Collectors.groupingBy(MemberInfoVo::getLabMemberId));

		List<Long> commentIds = commentList.stream().map(Comments::getId).collect(Collectors.toList());
		List<FileManage> fileList = fileManageService.selectList(OssFileEnum.CommentFile, commentIds);
		Map<Long, List<FileManage>> fileMap = fileList.stream()
				.collect(Collectors.groupingBy(FileManage::getReferDataId));

		commentList.forEach(comment -> {
			CommentsListVo vo = MyBeanUtils.copyBean(comment, CommentsListVo.class);
			List<MemberInfoVo> memberVo = memberMap.get(vo.getLabMemberId());
			if (CollUtil.isNotEmpty(memberVo)) {
				vo.setName(memberVo.get(0).getUserName());
				vo.setImageUrl(memberVo.get(0).getImageUrl());
			}
			if (vo.getContentType() != 0 && CollUtil.isNotEmpty(fileMap)) {
				List<FileManage> files = fileMap.get(comment.getId());
				if (CollUtil.isNotEmpty(files)) {
					vo.setFileManage(files.get(0));
				}
			}
			listVos.add(vo);
		});
		return listVos;
	}

	/**
	 * 聊天成员
	 * 
	 * @param labId
	 * @param labMemberId
	 * @return
	 */
	public List<ChatMemberListVo> getChatMemberList(Long labId, Long labMemberId) {
		List<ChatMemberListVo> voList = CollUtil.toList();
		List<MemberInfoVo> memberVoList = labMemberService.selectMemberVoList(labId,
				LabMemberEnum.State.STATE_IN.getValue());
		if (CollUtil.isNotEmpty(memberVoList)) {
			memberVoList.forEach(memberVo -> {
				ChatMemberListVo chatMember = MyBeanUtils.copyBean(memberVo, ChatMemberListVo.class);
				ChatMessage message = chatMessageService.getNewestOneMessage(labMemberId, memberVo.getLabMemberId());
				if (message != null) {
					int noReadNum = chatMessageService.noReadNum(labMemberId, message.getFromMemberId());
					chatMember.setNoReadNum(noReadNum);
					chatMember.setMessageDate(message.getCreateTime());
					if (CommentsContentTypeEnum.TEXT.getValue().equals(message.getContentType())
							|| CommentsContentTypeEnum.CARD.getValue().equals(message.getContentType())) {
						chatMember.setContent(message.getContent());
					} else {
						chatMember.setContent("[" + CommentsContentTypeEnum.getKey(message.getContentType()) + "]");
					}
				}
				voList.add(chatMember);
			});
			return chatMemberSort(voList);
		}
		return voList;
	}

	// 聊天成员排序
	private List<ChatMemberListVo> chatMemberSort(List<ChatMemberListVo> voList) {
		List<ChatMemberListVo> list = CollUtil.toList();
		if(CollUtil.isNotEmpty(voList)) {
			List<ChatMemberListVo> list1 = voList.stream().filter(vo -> vo.getMessageDate() != null).collect(Collectors.toList());
			if(CollUtil.isNotEmpty(list1)) {
				CollUtil.sort(list1, new Comparator<ChatMemberListVo>() {
					public int compare(ChatMemberListVo c1, ChatMemberListVo c2) {
						return c2.getMessageDate().compareTo(c1.getMessageDate());
					}
				});
				list.addAll(list1);
			}
			List<ChatMemberListVo> list2 = voList.stream().filter(vo -> vo.getMessageDate() == null).collect(Collectors.toList());
			if(CollUtil.isNotEmpty(list2)) {
				CollUtil.sort(list1, new Comparator<ChatMemberListVo>() {
					public int compare(ChatMemberListVo c1, ChatMemberListVo c2) {
						return c2.getUserName().compareTo(c1.getUserName());
					}
				});
				list.addAll(list2);
			}
		}
		
		return list;
	}

	/**
	 * 获取历史消息
	 * 
	 * @param meMemberId     自己
	 * @param otherMemberId   他人
	 * @param startMessageId 起始消息ID(获取该消息ID之前的消息20条)
	 * @return
	 */
	public List<ChatMessageVo> historyMessage(Long meMemberId, Long otherMemberId, Long startMessageId) {
		List<ChatMessage> historyMessage = chatMessageService.historyMessage(meMemberId, otherMemberId, startMessageId);
		chatMessageService.setAllMessageRead(meMemberId, otherMemberId);
		return getChatMessageVo(historyMessage);
	}

	/**
	 * 获取最新消息
	 * 
	 * @param meMemberId     自己
	 * @param otherMemberId   他人
	 * @param startMessageId 起始消息ID(获取该消息ID之后的消息)
	 * @return
	 */
	public List<ChatMessageVo> newestMessage(Long meMemberId, Long otherMemberId, Long startMessageId) {
		List<ChatMessage> newestMessage = chatMessageService.newestMessage(meMemberId, otherMemberId, startMessageId);
		chatMessageService.setAllMessageRead(meMemberId, otherMemberId);
		return getChatMessageVo(newestMessage);
	}

	// 获取消息VO列表
	private List<ChatMessageVo> getChatMessageVo(List<ChatMessage> messageList) {
		List<ChatMessageVo> voList = CollUtil.toList();
		if (CollUtil.isNotEmpty(messageList)) {
			Map<Long, List<FileManage>> fileMap = null;
			List<Long> fileIds = messageList.stream().map(ChatMessage::getFileId).collect(Collectors.toList());
			if (CollUtil.isNotEmpty(fileIds)) {
				List<FileManage> fileList = fileManageService.selectListByIds(fileIds);
				fileMap = fileList.stream().collect(Collectors.groupingBy(FileManage::getId));
			}

			List<ChatMessage> cardList = messageList.stream().filter(new Predicate<ChatMessage>() {
				@Override
				public boolean test(ChatMessage message) {
					return CommentsContentTypeEnum.CARD.getValue().equals(message.getContentType());
				}
			}).collect(Collectors.toList());

			Map<Long, List<Experiment>> experimentMap = null;
			if (CollUtil.isNotEmpty(cardList)) {
				List<Long> experimentIds = cardList.stream().map(ChatMessage::getClassifyId)
						.collect(Collectors.toList());
				List<Experiment> experimentList = experimentService.selectByIds(experimentIds);
				if (CollUtil.isNotEmpty(experimentList)) {
					experimentMap = experimentList.stream().collect(Collectors.groupingBy(Experiment::getId));
				}
			}

			List<Long> fromMemberIds = messageList.stream().map(ChatMessage::getFromMemberId).collect(Collectors.toList());
			List<MemberInfoVo> memberVoList = labMemberService.selectMemberVoListByIds(fromMemberIds);
			Map<Long, List<MemberInfoVo>> memberVoMap = memberVoList.stream().collect(Collectors.groupingBy(MemberInfoVo::getLabMemberId));
			
			for (ChatMessage message : messageList) {
				ChatMessageVo vo = MyBeanUtils.copyBean(message, ChatMessageVo.class);
				MemberInfoVo member = memberVoMap.get(message.getFromMemberId()).get(0);
				vo.setUserName(member.getUserName());
				vo.setImageUrl(member.getImageUrl());
				if (CommentsContentTypeEnum.CARD.getValue().equals(message.getContentType()) && CollUtil.isNotEmpty(experimentMap)) {
					List<Experiment> experimentVos = experimentMap.get(message.getClassifyId());
					if (CollUtil.isNotEmpty(experimentVos)) {
						Experiment experiment = experimentVos.get(0);
						ExperimentCardVo cardVo = MyBeanUtils.copyBean(experiment, ExperimentCardVo.class);
						cardVo.setExperimentId(experiment.getId());
						cardVo.setMethodTypeName(experiment.getName());						
						vo.setCardVo(cardVo);
						voList.add(vo);
					}
				} else if (message.getFileId() != null && CollUtil.isNotEmpty(fileMap)) {
					List<FileManage> list = fileMap.get(message.getFileId());
					if (CollUtil.isNotEmpty(list)) {
						vo.setFileManage(list.get(0));
						voList.add(vo);
					}
				}else {
					voList.add(vo);
				}
			}

		}
		return voList;
	}

	/**
	 * 发送聊天信息
	 * 
	 * @param labMemberId
	 * @param addVo
	 * @return
	 */
	public Long addChatMessage(Long labId, Long fromMemberId, ChatMessageAddVo addVo) {
		ChatMessage chatMessage = MyBeanUtils.copyBean(addVo, ChatMessage.class);
		chatMessage.setFromMemberId(fromMemberId);
		if(CommentsClassifyEnum.PLAN.getValue().equals(addVo.getClassify())) {
			DateTime beginOfWeek = DateUtil.beginOfWeek(addVo.getPlanDate());
			DateTime endOfWeek = DateUtil.endOfWeek(addVo.getPlanDate());
			String title = StrUtil
					.builder("计划 ", DateUtil.format(beginOfWeek, "MM.dd"), "~", DateUtil.format(endOfWeek, "MM.dd"))
					.toString();
			chatMessage.setTitle(title);
			chatMessage.setRemark(String.valueOf(addVo.getPlanDate().getTime()));
		}else if(CommentsClassifyEnum.EXPERIMENT.getValue().equals(addVo.getClassify())) {
			Experiment experiment = experimentService.selectById(addVo.getClassifyId());
			TopicTarget topicTarget = topicTargetService.selectById(experiment.getTopicTargetId());
			String title = experiment.getName()+"//"+topicTarget.getName();
			String[] strArr = experiment.getName().split(":");
			if(strArr!=null && strArr.length>1 && StrUtil.isNotBlank(strArr[1])) {
				title = strArr[1]+"//"+topicTarget.getName();
			}
			chatMessage.setTitle(title);
		}
		
		if (!CommentsClassifyEnum.CHAT.getValue().equals(addVo.getClassify())) {// 同步评论并发送聊天消息给相关人
			Comments comments = new Comments();
			comments.setLabMemberId(fromMemberId);
			comments.setClassify(chatMessage.getClassify());
			comments.setClassifyId(chatMessage.getClassifyId());
			comments.setContentType(chatMessage.getContentType());
			comments.setContent(chatMessage.getContent());
			comments.setRemark(chatMessage.getRemark());
			commentsService.save(comments);
			chatMessage.setCommentId(comments.getId());
			
			this.asyncSendChat(labId, comments, addVo.getFileId(), CollUtil.toList(addVo.getToMemberId()));
		}
		chatMessageService.save(chatMessage);
		
		if (addVo.getFileId() != null) {
			FileManage fileManage = new FileManage();
			fileManage.setId(addVo.getFileId());
			if(CommentsClassifyEnum.CHAT.getValue().equals(addVo.getClassify())) {
				fileManage.setAttachType(OssFileEnum.ChatMessageFile.getKey());
				fileManage.setReferDataId(chatMessage.getId());
			}else {
				fileManage.setAttachType(OssFileEnum.CommentFile.getKey());
				fileManage.setReferDataId(chatMessage.getCommentId());
			}
			fileManageService.updateById(fileManage);
		}
		return chatMessage.getId();
	}
	
	/**
	 * 发送实验卡内容消息
	 * @param labId
	 * @param labMemberId
	 * @param experimentId
	 * @param content
	 */
	public void sendExperimentCard(Long labId, Long labMemberId, Long experimentId, String content) {
		Comments comments = new Comments();
		comments.setLabMemberId(labMemberId);
		comments.setClassify(CommentsClassifyEnum.EXPERIMENT.getValue());
		comments.setClassifyId(experimentId);
		comments.setContentType(CommentsContentTypeEnum.CARD.getValue());
		comments.setContent(content);
		this.asyncSendChat(labId, comments, null, CollUtil.toList(labMemberId));
	}

	
	/**
	 * 查询未读总数
	 * @param labMemberId
	 * @return
	 */
	public int noReadTotalNum(Long labMemberId) {
		return chatMessageService.noReadNum(labMemberId, null);
	}

	/**
	 * 查找聊天记录
	 * 
	 * @param searchVo
	 * @return
	 */
	public PageVo<ChatMessageVo> searchContent(ChatContentSearchVo searchVo) {
		PageVo<ChatMessage> page = chatMessageService.searchContent(searchVo);
		if (page != null && CollUtil.isNotEmpty(page.getContent())) {
			List<ChatMessageVo> list = getChatMessageVo(page.getContent());
			return new PageVo<ChatMessageVo>(page.getPageNum(), page.getPageSize(), page.getTotalRow(), list);
		}
		return new PageVo<ChatMessageVo>(searchVo.getPageNum(), searchVo.getPageSize());
	}
	
	/**
	 * 查找图片记录
	 * 
	 * @param searchVo
	 * @return
	 */
	public List<ChatSearchFileVo> searchPicture(ChatFileSearchVo searchVo) {
		return chatMessageService.searchPicture(searchVo);
	}

	
	/**
	 * 查找聊天分类记录
	 * 
	 * @return
	 */
	public PageVo<ChatSearchClassifyVo> searchClassify(ChatClassifySearchVo searchVo) {
		return chatMessageService.searchClassify(searchVo);
	}
	
	

	/**
	 * 判断消息内容来源是否删除
	 * 
	 * @param messageId
	 * @return
	 */
	public void sourceIsDelete(Integer classify, Long classifyId) {
		
		if(CommentsClassifyEnum.EXPERIMENT.getValue().equals(classify)) {
			Experiment experiment = experimentService.selectById(classifyId);
			Assert.isTrue(experiment!=null && BoolEnum.FALSE.getValue().equals(experiment.getIsDelete()), "实验已被删除");
			TopicExperiment topicExperiment = topicExperimentService.selectById(experiment.getTopicExperimentId());
			Assert.isTrue(topicExperiment!=null && BoolEnum.FALSE.getValue().equals(topicExperiment.getIsDelete()), "实验目标已被删除");
			TopicTarget target = topicTargetService.selectById(experiment.getTopicTargetId());
			Assert.isTrue(target!=null && BoolEnum.FALSE.getValue().equals(target.getIsDelete()), "实验流已被删除");
			TopicDirection direction = topicDirectionService.getById(experiment.getTopicDirectionId());
			Assert.isTrue(direction!=null && BoolEnum.FALSE.getValue().equals(direction.getIsDelete()), "研究内容已被删除");
			Topic topic = topicService.selectById(experiment.getTopicId());
			Assert.isTrue(topic!=null && BoolEnum.FALSE.getValue().equals(topic.getIsDelete()), "课题已被删除");
			
		} else if(CommentsClassifyEnum.PLAN.getValue().equals(classify)) {
			LabMember member = labMemberService.selectById(classifyId);
			Assert.isTrue(member!=null && BoolEnum.TRUE.getValue().equals(member.getState()), "成员已退出实验室");
			
		} else if(CommentsClassifyEnum.TOPIC.getValue().equals(classify)) {
			Topic topic = topicService.selectById(classifyId);
			Assert.isTrue(topic!=null && BoolEnum.FALSE.getValue().equals(topic.getIsDelete()), "课题已被删除");
			
		} else if(CommentsClassifyEnum.TOPIC_DIRECTION.getValue().equals(classify)) {
			TopicDirection direction = topicDirectionService.getById(classifyId);
			Assert.isTrue(direction!=null && BoolEnum.FALSE.getValue().equals(direction.getIsDelete()), "研究内容已被删除");
			Topic topic = topicService.selectById(direction.getTopicId());
			Assert.isTrue(topic!=null && BoolEnum.FALSE.getValue().equals(topic.getIsDelete()), "课题已被删除");
			
		} else if(CommentsClassifyEnum.TOPIC_TARGET.getValue().equals(classify)) {
			TopicTarget target = topicTargetService.selectById(classifyId);
			Assert.isTrue(target!=null && BoolEnum.FALSE.getValue().equals(target.getIsDelete()), "实验流已被删除");
			TopicDirection direction = topicDirectionService.getById(target.getTopicDirectionId());
			Assert.isTrue(direction!=null && BoolEnum.FALSE.getValue().equals(direction.getIsDelete()), "研究内容已被删除");
			Topic topic = topicService.selectById(target.getTopicId());
			Assert.isTrue(topic!=null && BoolEnum.FALSE.getValue().equals(topic.getIsDelete()), "课题已被删除");
		} 
		
	}

	/**
	 * 获取计划评论列表
	 * @param labMemberId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public List<CommentsListVo> getPlanList(Long labMemberId, Long planMemberId, Date startDate, Date endDate) {
		List<CommentsListVo> listVos = CollUtil.toList();
		List<Comments> commentList = commentsService.getPlanList(planMemberId, startDate, endDate);
		if (CollUtil.isNotEmpty(commentList)) {
			listVos.addAll(getCommentsVoList(commentList));
		}
		// 把聊天消息相关的评论标记为已读
		chatMessageService.setMessageRead(labMemberId, CommentsClassifyEnum.PLAN.getValue(), planMemberId);
		return listVos;
	}
	
	
	
	

	

}
